package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.woniuxy.entity.OrdeItem;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.ShoppingCart;
import com.woniuxy.entity.dto.OrderParamDTO;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.producer.DelayProducer;
import com.woniuxy.service.OrderService;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.SnowflakeIdGenerator;
import com.woniuxy.util.UserConenxt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author dingpf
 * @version 1.0
 * @description
 * @create 2025/4/27 9:58
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private DelayProducer delayProducer;

    /**
     * 用户下单接口
     * 1：校验该该书籍库存是否足够
     * 2：写入订单表
     * 3：写入订单详情表
     * 4：把购物车书籍状态改成已下单
     * 5：维护书籍的库存量
     * 6：超过15分钟没有付款取消订单
     *
     * @return
     */
    @Override
    @Transactional
    public ResponseData<?> addOrder(OrderParamDTO orderParamDTO) throws InterruptedException, ParseException {
        //1：校验该该书籍库存是否足够
        List<ShoppingCart> shoppingCarts = orderMapper.checkBookCount(orderParamDTO.getIds());

//        List<String> bookNotEnough = new ArrayList<>();
//        for (ShoppingCart shoppingCart : shoppingCarts) {
//            if (shoppingCart.getBuyNum() > shoppingCart.getStoreCount()){
//                //证明该书籍库存不够
//                bookNotEnough.add(shoppingCart.getName());
//            }
//        }
        List<String> bookNotEnough = shoppingCarts.stream()
                                .filter(e -> e.getBuyNum() > e.getStoreCount())
                                .map(e -> e.getName()) //映射
                                .collect(Collectors.toList());


        if (!CollectionUtils.isEmpty(bookNotEnough)){
            //把库存不足书籍直接返回
            return ResponseData.ok(bookNotEnough);
        }
        //2：写入订单表
        Order order = new Order();
        Integer userId = UserConenxt.getUserId();
        order.setUserId(userId);
        order.setAddressId(orderParamDTO.getAddrId());
        //new BigDecimal(0)
        BigDecimal totalPrice = BigDecimal.ZERO;

        for (ShoppingCart shoppingCart : shoppingCarts) {
            totalPrice = totalPrice.add(shoppingCart.getPrice().multiply(new BigDecimal(shoppingCart.getBuyNum())));

        }
        order.setTotalPrice(totalPrice);

        //获取雪花Id
        SnowflakeIdGenerator sfg = new SnowflakeIdGenerator();

        String orderNum = String.valueOf(sfg.nextId());
        order.setOrderNum(orderNum); //订单编号

        orderMapper.addOrder(order);

        //3：写入订单详情表
        List<OrdeItem> orderItems = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrdeItem ordeItem = new OrdeItem();
            ordeItem.setBookId(shoppingCart.getBookId());
            ordeItem.setBookName(shoppingCart.getName());
            ordeItem.setOrderId(orderNum);
            ordeItem.setBuyCount(shoppingCart.getBuyNum());
            ordeItem.setPrice(shoppingCart.getPrice());
            ordeItem.setSumPrice(shoppingCart.getPrice().multiply(new BigDecimal(shoppingCart.getBuyNum())));

            orderItems.add(ordeItem);
        }

        orderMapper.batchAddOrderItem(orderItems);

        //4：把购物车书籍状态改成已下单
        orderMapper.batchUpdateShoppingCartStat(orderParamDTO.getIds());

        //5：维护书籍的库存量(延迟双删修改)
        orderMapper.batchUpdateBookCount(shoppingCarts);

        //6：超过15分钟没有付款取消订单
        Integer TTL = 15 * 60 * 1000;
        delayProducer.send(orderNum,"delay",15000);

        return ResponseData.ok();
    }
}
